#ifndef _CONVEXITY_SLKJ223B4K_
#define _CONVEXITY_SLKJ223B4K_
#include <stdio.h>
#include <iostream>
using namespace std;
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;

// 检测以a，b两点为端点的线是否在mask中
static bool testline(Mat mask_gray, Point a, Point b)  
{  
    if (a.y<b.y)  
    {  
        double ratio = 1.0*(a.x - b. x)/(a.y - b.y);  
  
        for (int i = a.y+1; i<b.y; i++)  
            if (mask_gray.at<uchar>(i, a.x+ratio*(i-a.y)) == 0)  
                return false;  
    }  
    else if (a.y>b.y)  
    {  
        double ratio = 1.0*(a.x - b. x)/(a.y - b.y);  
  
        for (int i = b.y+1; i<a.y; i++)  
            if (mask_gray.at<uchar>(i, b.x+ratio*(i-b.y)) == 0)  
                return false;  
    }  
    else  
    {  
        if (a.x > b.x)  
        {  
            for (int i = b.x+1; i<a.x; i++)  
                if (mask_gray.at<uchar>(a.y, i) == 0)  
                    return false;  
        }  
        else  
        {  
            for (int i = a.x+1; i<b.x; i++)  
                if (mask_gray.at<uchar>(a.y, i) == 0)  
                    return false;  
        }  
    }  
      
    return true;  
}

//本程序为计算凸性，输入图像为一个单独的obj  
double convexity(Mat mask)  
{  
    Mat mask_gray;  
    //cvtColor(mask, mask_gray, CV_BGR2GRAY);  
    assert(mask.type() == CV_8UC1);  
    mask_gray = mask;  
  
    //轮廓检测， 并确保只有一个obj  
    vector<vector<Point> > contours;  
    vector<Vec4i> hierarchy;  
  
    findContours(mask_gray.clone(), contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_NONE);  
    cout << ">> contours size: " << (int)contours.size() << endl;
    assert(contours.size() == 1);  
  
    vector<Point> sampling_points;  
    int sampling_num = 50;  
  
    if (contours[0].size()<=sampling_num)  
    {  
        sampling_points = contours[0];  
    }  
    else  
    {  
        double space = contours[0].size()*1.0/sampling_num;  
  
        for (int i = 0; i< sampling_num; i++)  
        {  
            sampling_points.push_back(contours[0][(int)(i*space)]);  
        }  
    }  
  
    double all = 0;//总次数  
    double right = 0;//对的次数  
  
    for (int i = 0; i< sampling_points.size(); i++)  
    {  
        for (int j = i+1; j< sampling_points.size(); j++)  
        {  
            Point a = sampling_points[i];  
            Point b = sampling_points[j];  
  
            if ((a.y == b.y)  
                &&(a.x == b.x))  
            {  
                cout<<"error"<<endl;  
            }  
  
            all++;  
  
            if (testline(mask_gray, a, b))  
            {  
                right++;  
            }  
        }  
    }  
      
    return 1.0*right/all;  
}  

#endif
